package cn.com.digitalnet.ad.util;

import java.io.File;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
public class FileUploader {

	@Autowired
	PropertiesHolder holder;

	public String doUpload(MultipartFile file) {
		try {
			String ext = StringUtils.substringAfterLast(
					file.getOriginalFilename(), ".");

			String fileName = UUID.randomUUID().toString() + "." + ext;
			file.transferTo(new File(holder.getUploadPath() + fileName));
			return fileName;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public File doImport(MultipartFile file) {
		try {
			String ext = StringUtils.substringAfterLast(
					file.getOriginalFilename(), ".");

			String fileName = UUID.randomUUID().toString() + "." + ext;
			File diskFile = new File(holder.getUploadPath() + fileName);
			file.transferTo(diskFile);

			return diskFile;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public String uploadFile(MultipartFile file, String ext) {
		try {
			 String fileName = UUID.randomUUID().toString()+ "." + ext;
//			String fileName = file.getOriginalFilename();
			file.transferTo(new File(holder.getUploadPath() + fileName));
			return fileName;
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	public String uploadLogo(MultipartFile file) {
		String ext = StringUtils.substringAfterLast(file.getOriginalFilename(),
				".");

		String fileName = uploadFile(file, ext);
		File img = new File(holder.getUploadPath() + fileName);
		// 大
		new ImageUtil().resizeImage(img, new File(holder.getUploadPath()
				+ fileName + "_big.png"), 200, 140);
		// 小
		new ImageUtil().resizeImage(img, new File(holder.getUploadPath()
				+ fileName + "_small.png"), 100, 70);
		return fileName;
	}

	public String uploadAttac(MultipartFile file) {
		// TODO Auto-generated method stub
		String ext = StringUtils.substringAfterLast(file.getOriginalFilename(),
				".");

		String fileName = uploadFile(file, ext);
		return fileName;
	}
}
